package com.group2.operations.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.group2.operations.common.api.ApiErrorCode;
import com.group2.operations.common.api.ApiResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 给shiro增加过滤器，过滤OPTIONS请求
 * 提示未登录
 */
public class CORSAuthenticationFilter extends FormAuthenticationFilter{
    private static final Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class);

    public CORSAuthenticationFilter() {
        super();
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //总是放行OPTIONS请求
        if(((HttpServletRequest)request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setStatus(HttpServletResponse.SC_OK);
        res.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        res.getWriter().println(objectMapper.writeValueAsString(ApiResult.failed(ApiErrorCode.UNAUTHORIZED)));

        return false;
    }
}
